<?php
/**
 * Created by PhpStorm.
 * User: hanbin
 * Date: 17/3/29
 * Time: 下午10:59
 */

namespace App\Server;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class BaseModel extends Model
{
    private static $tableName;

    public function __construct()
    {
        parent::__construct();
        self::$tableName = $this->table;
    }

    /**
     * 分页获取列表
     *
     * @param int $pagesize
     * @param string $field
     * @param int $lastid
     * @param array $so
     * @return array
     */
    public static function getList($pagesize = 10, $field = '', $lastid = 1, $so = [])
    {
        $result = null;
        if ($so) {
            $result = self::where($so)->orderBy('id', 'desc')->paginate($pagesize, $field, null, $lastid);
        } else {
            $result = self::orderBy('id', 'desc')->paginate($pagesize, $field, null, $lastid);
        }
        $_result = [];
        if ($result) {
            $data = [];
            foreach ($result as $k => $v) {
                $data[] = $v;
            }
            $_result['data'] = $data;
            $_result['total'] = $result->total();
            $_result['count'] = $result->count();
            $_result['currentPage'] = $result->currentPage();
            $_result['firstItem'] = $result->firstItem();
            $_result['lastItem'] = $result->lastItem();
//            $_result['hasMorePages'] = $result->hasMorePages();
            $_result['lastPage'] = $result->lastPage();
//            $_result['nextPageUrl'] = $result->nextPageUrl();
            $_result['perPage'] = $result->perPage();
//            $_result['previousPageUrl'] = $result->previousPageUrl();
            $_result['pagesize'] = $result->perPage();
        }

        return $_result;
    }

    /**
     * 查询一条
     * @param array $so
     * @return bool
     */
    public static function first($so = [])
    {
        if ($so) {
            return self::where($so)->first();
        } else {
            return false;
        }
    }

    /**
     * 新增一条数据
     *
     * @param array $data
     * @return bool
     */
    public static function add($data = [])
    {
        if ($data) {
            return self::insert($data);
        } else {
            return false;
        }
    }

    /**
     * 更新
     *
     * @param array $so
     * @param array $data
     * @return bool
     */
    public static function updated($so = [], $data = [])
    {
        if ($so && $data) {
            return DB::table(self::$tableName)->where($so)->update($data);
        } else {
            return false;
        }
    }


}